package com.zzyl.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.WechatLoginMapper;
import com.zzyl.properties.JWTConfigProperties;
import com.zzyl.properties.WeChatConfigProperties;
import com.zzyl.service.WechatLoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UUID;
import com.zzyl.vo.LoginVo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.invoke.StringConcatException;
import java.util.HashMap;
import java.util.Map;

import static cn.hutool.extra.servlet.ServletUtil.getParamMap;

/**
 * @Author: Learner
 * @Version: 1.0
 */
@Service
@Transactional
public class WechatLoginServiceImpl implements WechatLoginService {
    @Autowired
    private WechatLoginMapper wechatLoginMapper;
    @Autowired
    private WeChatConfigProperties weChat;

    @Autowired
    private JWTConfigProperties jwt;

    private static final Map<String, String> map=new HashMap<>();

    String[] arr = {"老鼠", "大米", "猫咪", "鱼头"};

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.根据登录code调用微信用户微信登录接口获取用户的openId
        String code = userLoginRequestDto.getCode();
        String openId = getOpenId(code);
        //2.需要客户表用来存储微信用户的信息

        //3.如果是新用户{根据openId到客人表中查询}
        Member member = wechatLoginMapper.getByOpenId(openId);
        String nickName = "";
        if (member == null) {
            /*int c = RandomUtil.randomInt(0, 3);
            nickName = arr[c];*/
            nickName = UUID.randomUUID().toString();
            member = new Member();
            member.setOpenId(openId);
            member.setName(nickName);
            wechatLoginMapper.insertMember(member);
        } else {
            nickName = member.getName();
        }

        //4.根据openid 和手机号code获取当前用户手机号

        String phoneCode = userLoginRequestDto.getPhoneCode();
        String phone = getPhone(phoneCode,code,openId,getAccessToken());
        //5.需要将用户的手机号跟新到客户表中 根据id修改
        Long id = member.getId();
        wechatLoginMapper.updateMember(id,phone);
        //6.前面的步骤走完后能够获取到一个客户ID

        //7.给客户颁发令牌，数据返回给前端

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        String token = JwtUtil.createJWT(this.jwt.getBase64EncodedSecretKey(), this.jwt.getTtl(), claims);


        return LoginVo.builder().token(token).nickName(nickName).build();
    }

    private String getOpenId(String code) {
        Map<String, Object> paramMap = getParam();
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        HttpResponse response = HttpUtil.createRequest(Method.GET, weChat.getRequestUrl())
                .form(paramMap)
                .execute();
        String body = response.body();
        String openid = JSONUtil.parseObj(body).get("openid").toString();
        return openid;
    }

    private Map<String, Object> getParam() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", weChat.appId);
        paramMap.put("secret", weChat.appSecret);
        return paramMap;
    }


    private String getAccessToken() {
        String accessToken = map.get("access_token");
        if (StrUtil.isEmpty(accessToken)) {
            Map<String, Object> paramMap = getParam();
            paramMap.put("grant_type", "client_credential");
            HttpResponse response = HttpUtil.createRequest(Method.GET, weChat.getTokenUrl())
                    .form(paramMap)
                    .execute();
            String body = response.body();
            accessToken = JSONUtil.parseObj(body).get("access_token").toString();
            map.put("access_toke", accessToken);
        }
        return accessToken;
    }


    private String getPhone(String phoneCode,String code,String openid,String accessToken){
        Map<String,String> phoneMap=new HashMap<>();
        phoneMap.put("code" ,phoneCode);
        phoneMap.put("openid" ,openid);
        HttpResponse response = HttpUtil.createRequest(Method.POST, weChat.getPhoneRequestUrl()+accessToken)
                .body(JSONUtil.toJsonStr(phoneMap))
                .execute();
        String body = response.body();
        String phoneNum = JSONUtil.parseObj(body).getJSONObject("phone_info").get("phoneNumber").toString();
        return phoneNum;

    }
}
